import { createRouter, createWebHistory, RouteRecordRaw } from 'vue-router'
import axios from 'axios'
import store from '@/store'

const routes: Array<RouteRecordRaw> = [
  {
    path: '/',
    name: 'home',
    component: () => import('../views/HomeIndex.vue')
  },
  {
    path: '/login',
    name: 'login',
    component: () => import('../views/LoginIndex.vue'),
    meta: { redirectAlredyLogin: true }
  },
  {
    path: '/signup',
    name: 'signup',
    component: () => import('../views/SignUp.vue'),
    meta: { redirectAlredyLogin: true }
  },
  {
    path: '/column/:id',
    name: 'column',
    component: () => import('../views/ColumnDetail.vue'),
    meta: { requiredLogin: true }
  },
  {
    path: '/post/:_id',
    name: 'post',
    component: () => import('../views/PostDetail.vue')
  },
  {
    path: '/create',
    name: 'create',
    component: () => import('../components/CreatePost.vue'),
    meta: { requiredLogin: true }
  }
]

const router = createRouter({
  history: createWebHistory(process.env.BASE_URL),
  routes
})

// to: 要进入的目标
// from: 要离开的目标
// next(): 如果有 next() 方法跳转 指向下一个路由
// router.beforeEach((to, from, next) => {
//   if (to.name !== 'login' && !store.state.user.isLogin) {
//     next({ name: 'login' })
//   } else {
//     next()
//   }
// })

// 通过路由原信息
router.beforeEach((to, from, next) => {
  const { user, token } = store.state
  const { redirectAlredyLogin, requiredLogin } = to.meta
  if (!user.isLogin) {
    // 没有登录
    if (token) {
      axios.defaults.headers.common.Authorization = `Bearer ${token}`
      store
        .dispatch('fetchCurrentUser')
        .then(() => {
          if (redirectAlredyLogin) {
            next('/')
          } else {
            next()
          }
        })
        .catch((e) => {
          console.log(e)
          store.commit('logout')
          next('/login')
        })
    } else {
      if (requiredLogin) {
        next('/login')
      } else {
        next()
      }
    }
  } else {
    // 登录
    if (redirectAlredyLogin) {
      next('/')
    } else {
      next()
    }
  }
})

export default router
